<template>
  <div class="servers-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>集群管理</h2>
      <div class="header-actions">
        <el-button type="primary" :icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button type="success" :icon="Plus" @click="addServer">
          添加节点
        </el-button>
      </div>
    </div>

    <!-- 集群概览统计 -->
    <el-row :gutter="20" class="stats-row compact">
      <el-col :span="6" v-for="stat in clusterStats" :key="stat.title">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact" :color="stat.color">
              <component :is="stat.icon" />
            </el-icon>
            <div>
              <div class="stat-number compact">{{ stat.value }}</div>
              <div class="stat-label compact">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 服务器列表 -->
    <div class="servers-list">
      <el-row :gutter="20">
        <el-col :span="12" v-for="server in servers" :key="server.id">
          <el-card class="server-card" :class="`status-${server.status}`">
            <template #header>
              <div class="server-header">
                <div class="server-info">
                  <h3>{{ server.name }}</h3>
                  <span class="server-ip">{{ server.ip }}</span>
                  <el-tag :type="getStatusType(server.status)" size="small">
                    {{ getStatusText(server.status) }}
                  </el-tag>
                </div>
                <div class="server-actions">
                  <el-button 
                    size="small" 
                    :type="server.status === 'online' ? 'warning' : 'success'"
                    @click="toggleServer(server)">
                    {{ server.status === 'online' ? '下线' : '上线' }}
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 系统资源监控 -->
            <div class="resource-monitor">
              <h4>系统资源</h4>
              <div class="resource-grid">
                <!-- CPU 使用率 -->
                <div class="resource-item">
                  <div class="resource-header">
                    <span>CPU</span>
                    <span :class="getResourceClass(server.cpu)">
                      {{ server.cpu }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="server.cpu" 
                    :color="getProgressColor(server.cpu)"
                    :stroke-width="6"
                    striped
                    striped-flow />
                </div>

                <!-- 内存使用率 -->
                <div class="resource-item">
                  <div class="resource-header">
                    <span>内存</span>
                    <span :class="getResourceClass(server.memory)">
                      {{ server.memory }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="server.memory" 
                    :color="getProgressColor(server.memory)"
                    :stroke-width="6"
                    striped
                    striped-flow />
                  <div class="resource-detail">
                    {{ formatBytes(server.memory_used) }} / {{ formatBytes(server.memory_total) }}
                  </div>
                </div>

                <!-- 磁盘使用率 -->
                <div class="resource-item">
                  <div class="resource-header">
                    <span>磁盘</span>
                    <span :class="getResourceClass(server.disk)">
                      {{ server.disk }}%
                    </span>
                  </div>
                  <el-progress 
                    :percentage="server.disk" 
                    :color="getProgressColor(server.disk)"
                    :stroke-width="6"
                    striped
                    striped-flow />
                  <div class="resource-detail">
                    {{ formatBytes(server.disk_used) }} / {{ formatBytes(server.disk_total) }}
                  </div>
                </div>

                <!-- 网络状态 -->
                <div class="resource-item">
                  <div class="resource-header">
                    <span>网络</span>
                    <span :class="server.network.status">
                      {{ server.network.status === 'up' ? '正常' : '异常' }}
                    </span>
                  </div>
                  <div class="network-stats">
                    <div>
                      <el-icon><Top /></el-icon>
                      {{ formatBytes(server.network.upload) }}/s
                    </div>
                    <div>
                      <el-icon><Bottom /></el-icon>
                      {{ formatBytes(server.network.download) }}/s
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 服务状态监控 -->
            <div class="services-monitor">
              <h4>服务状态</h4>
              <div class="services-grid">
                <div 
                  v-for="service in server.services" 
                  :key="service.name"
                  class="service-item"
                  :class="`status-${service.status}`">
                  <div class="service-icon">
                    <el-icon :size="20">
                      <component :is="getServiceIcon(service.name)" />
                    </el-icon>
                  </div>
                  <div class="service-info">
                    <div class="service-name">{{ service.display_name }}</div>
                    <div class="service-status">{{ service.status_text }}</div>
                  </div>
                  <el-tag 
                    :type="getServiceStatusType(service.status)" 
                    size="small"
                    effect="dark">
                    {{ getServiceStatusText(service.status) }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 最后更新时间 -->
            <div class="last-update">
              <el-icon><Clock /></el-icon>
              最后更新: {{ formatTime(server.last_update) }}
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加服务器对话框 -->
    <el-dialog
      v-model="addServerDialog"
      title="添加服务器"
      width="500px">
      <el-form :model="newServerForm" label-width="80px">
        <el-form-item label="服务器名称">
          <el-input v-model="newServerForm.name" placeholder="请输入服务器名称" />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="newServerForm.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口号">
          <el-input v-model="newServerForm.port" placeholder="默认: 22" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addServerDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddServer">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Plus,
  Monitor,
  Coin,
  Folder,
  Upload,
  Download,
  Top,
  Bottom,
  Clock,
  Setting,
  VideoCamera,
  Microphone,
  Picture
} from '@element-plus/icons-vue'

// 数据
const servers = ref([])
const loading = ref(false)
const addServerDialog = ref(false)
const newServerForm = ref({
  name: '',
  ip: '',
  port: ''
})

// 集群统计
const clusterStats = computed(() => [
  {
    title: '在线服务器',
    value: servers.value.filter(s => s.status === 'online').length,
    icon: Monitor,
    color: '#67C23A',
    status: 'success'
  },
  {
    title: '离线服务器',
    value: servers.value.filter(s => s.status === 'offline').length,
    icon: Monitor,
    color: '#F56C6C',
    status: 'error'
  },
  {
    title: '平均CPU使用率',
    value: Math.round(servers.value.reduce((sum, s) => sum + s.cpu, 0) / servers.value.length || 0) + '%',
    icon: Coin,
    color: '#409EFF',
    status: 'info'
  },
  {
    title: '平均内存使用率',
    value: Math.round(servers.value.reduce((sum, s) => sum + s.memory, 0) / servers.value.length || 0) + '%',
    icon: Folder,
    color: '#E6A23C',
    status: 'warning'
  }
])

// 模拟数据
const loadMockData = () => {
  servers.value = [
    {
      id: 1,
      name: '主服务器-01',
      ip: '192.168.1.100',
      status: 'online',
      cpu: 45,
      memory: 62,
      memory_used: 8589934592,
      memory_total: 13743895347,
      disk: 73,
      disk_used: 780140544000,
      disk_total: 1073741824000,
      network: {
        status: 'up',
        upload: 1048576,
        download: 5242880
      },
      services: [
        {
          name: 'nginx',
          display_name: 'Web服务器',
          status: 'running',
          status_text: '运行正常',
          port: 80
        },
        {
          name: 'mysql',
          display_name: '数据库',
          status: 'running',
          status_text: '运行正常',
          port: 3306
        },
        {
          name: 'redis',
          display_name: '缓存服务',
          status: 'running',
          status_text: '运行正常',
          port: 6379
        },
        {
          name: 'ffmpeg',
          display_name: '视频处理',
          status: 'running',
          status_text: '3个进程',
          port: null
        }
      ],
      last_update: new Date()
    },
    {
      id: 2,
      name: '转码服务器-02',
      ip: '192.168.1.101',
      status: 'online',
      cpu: 78,
      memory: 85,
      memory_used: 11811160064,
      memory_total: 13743895347,
      disk: 65,
      disk_used: 698351607808,
      disk_total: 1073741824000,
      network: {
        status: 'up',
        upload: 2097152,
        download: 10485760
      },
      services: [
        {
          name: 'ffmpeg',
          display_name: '视频转码',
          status: 'running',
          status_text: '5个任务',
          port: null
        },
        {
          name: 'nginx',
          display_name: '文件服务',
          status: 'running',
          status_text: '运行正常',
          port: 8080
        },
        {
          name: 'redis',
          display_name: '缓存服务',
          status: 'warning',
          status_text: '内存使用高',
          port: 6379
        }
      ],
      last_update: new Date()
    },
    {
      id: 3,
      name: '存储服务器-03',
      ip: '192.168.1.102',
      status: 'offline',
      cpu: 0,
      memory: 0,
      disk: 0,
      network: {
        status: 'down',
        upload: 0,
        download: 0
      },
      services: [
        {
          name: 'nginx',
          display_name: '文件服务',
          status: 'stopped',
          status_text: '服务停止',
          port: 80
        }
      ],
      last_update: new Date(Date.now() - 3600000)
    }
  ]
}

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    loadMockData()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

const addServer = () => {
  addServerDialog.value = true
}

const confirmAddServer = () => {
  // 添加服务器逻辑
  ElMessage.success('服务器添加成功')
  addServerDialog.value = false
  newServerForm.value = { name: '', ip: '', port: '' }
}

const toggleServer = (server) => {
  server.status = server.status === 'online' ? 'offline' : 'online'
  ElMessage.success(`${server.name}已${server.status === 'online' ? '上线' : '下线'}`)
}

// 工具函数
const getStatusType = (status) => {
  const map = {
    online: 'success',
    offline: 'danger',
    warning: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    online: '在线',
    offline: '离线',
    warning: '警告'
  }
  return map[status] || status
}

const getResourceClass = (value) => {
  if (value >= 90) return 'danger'
  if (value >= 75) return 'warning'
  return 'normal'
}

const getProgressColor = (value) => {
  if (value >= 90) return '#F56C6C'
  if (value >= 75) return '#E6A23C'
  return '#67C23A'
}

const getServiceIcon = (serviceName) => {
  const icons = {
    nginx: Setting,
    mysql: Monitor,
    redis: Coin,
    ffmpeg: VideoCamera,
    'live-streaming': VideoCamera,
    'file-service': Folder
  }
  return icons[serviceName] || Setting
}

const getServiceStatusType = (status) => {
  const map = {
    running: 'success',
    stopped: 'danger',
    warning: 'warning',
    error: 'danger'
  }
  return map[status] || 'info'
}

const getServiceStatusText = (status) => {
  const map = {
    running: '运行中',
    stopped: '已停止',
    warning: '警告',
    error: '错误'
  }
  return map[status] || status
}

const formatBytes = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatTime = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadMockData()
  
  // 模拟实时数据更新
  const interval = setInterval(() => {
    servers.value.forEach(server => {
      if (server.status === 'online') {
        // 随机更新资源使用率
        server.cpu = Math.max(0, Math.min(100, server.cpu + (Math.random() - 0.5) * 5))
        server.memory = Math.max(0, Math.min(100, server.memory + (Math.random() - 0.5) * 3))
        server.network.upload += (Math.random() - 0.5) * 100000
        server.network.download += (Math.random() - 0.5) * 500000
      }
    })
  }, 5000)

  onUnmounted(() => {
    clearInterval(interval)
  })
})
</script>

<style scoped>
.servers-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统一紧凑统计卡片样式 */
.stats-row {
  margin-bottom: 24px;
}

.stat-card.compact {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  box-shadow: none;
  transition: none;
  height: 48px;
}

.stat-card.compact:hover {
  box-shadow: none;
  transform: none;
}

.stat-content.compact {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0;
  height: 100%;
}

.stat-icon.compact {
  font-size: 20px;
  color: #3b82f6;
  flex-shrink: 0;
}

.stat-number.compact {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1;
}

.stat-label.compact {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
  line-height: 1;
}

/* 服务器列表样式 */
.servers-list {
  margin-top: 24px;
}

.server-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.server-card.status-offline {
  border-left: 4px solid #F56C6C;
}

.server-card.status-online {
  border-left: 4px solid #67C23A;
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.server-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.server-ip {
  color: #909399;
  margin-right: 12px;
}

.resource-monitor {
  margin-bottom: 20px;
}

.resource-monitor h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.resource-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.resource-item {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.resource-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.resource-header span:first-child {
  font-weight: 500;
  color: #606266;
}

.resource-header span:last-child {
  font-weight: bold;
}

.resource-header .danger {
  color: #F56C6C;
}

.resource-header .warning {
  color: #E6A23C;
}

.resource-header .normal {
  color: #67C23A;
}

.resource-detail {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.network-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #606266;
}

.network-stats > div {
  display: flex;
  align-items: center;
  gap: 4px;
}

.services-monitor h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.services-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.service-icon {
  padding: 8px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 50%;
  color: #409EFF;
}

.service-info {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: #303133;
}

.service-status {
  font-size: 12px;
  color: #909399;
}

.last-update {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

@media (max-width: 768px) {
  .resource-grid {
    grid-template-columns: 1fr;
  }
  
  .server-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>